package com.hymall.service.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hymall.bean.MarketRegion;
import com.hymall.bean.MarketRegionExample;
import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.CommonData;
import com.hymall.mapper.MarketRegionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 长平居士 - rolfcui@outlook.com
 * @description 位置模块 -> 地区列表实现
 * @date 2022/7/18 16:33
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    MarketRegionMapper marketRegionMapper;

    /**
     * @author 长平居士
     * @description 列出所有 省 市 县
     * @date 2022/7/18 21:38
     *
     * @param null
     * @return
     */
    @Override
    public CommonData<MarketRegion> list() {
        MarketRegionExample example = new MarketRegionExample();
        MarketRegionExample.Criteria criteria = example.createCriteria();

        // 逐级取出 省 市 县
        criteria.andTypeEqualTo((byte) 1);
        List<MarketRegion> provinces = marketRegionMapper.selectByExample(example);
        example.clear();

        criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte) 2);
        List<MarketRegion> cities = marketRegionMapper.selectByExample(example);
        example.clear();

        criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte) 3);
        List<MarketRegion> counties = marketRegionMapper.selectByExample(example);
        example.clear();

        // 自下而上逐级封装
        cities.forEach(city ->
                city.setChildren(counties.stream()
                        .filter(county -> city.getId() == county.getPid())
                        .collect(Collectors.toList()))
        );

        provinces.forEach(province ->
                province.setChildren(cities.stream()
                        .filter(city -> province.getId() == city.getPid())
                        .collect(Collectors.toList()))
        );

        // 包装成返回类型
        PageHelper.startPage(1, provinces.size());
        PageInfo<MarketRegion> pageInfo = new PageInfo<>(provinces);
        return CommonData.data(pageInfo);
    }
}
